'use strict'

const fs = require('fs');
const router = require('koa-router')();

function getFilePath(path) {
    let filePath = path || __dirname;
    let file = fs.readdirSync(filePath);
    let files = file.filter(item => {
        return item.endsWith('.js') && item !== 'index.js'
    })
    return files;
}

function registerRoute(router, files) {

    files.forEach(item => {
        let tmpPath = __dirname + '/' + item;
        let obj = require(tmpPath);

        for (let key in obj) {
            let tmpArr = key.split(' ');
            let tmpFn = obj[key];

            if (tmpArr[0] === 'get') {
                router.get(tmpArr[1], tmpFn)
            } else if (tmpArr[0] === 'post') {
                router.post(tmpArr[1], tmpFn)
            } else if (tmpArr[0] === 'put') {
                router.put(tmpArr[1], tmpFn)
            } else if (tmpArr[0] === 'delete') {
                router.delete(tmpArr[1], tmpFn)
            } else {
                console.log('方法错误！');
            }
        }
    });
    return router.routes();
}

module.exports = function () {
    let file = getFilePath();
    let fn = registerRoute(router, file)
    return fn;
}